package com.atguigu.yygh.order.controller.api;

import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeixinService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {
    @Autowired
    private WeixinService weixinPayService;

    @Autowired
    private PaymentService paymentService;
    /**
     * 下单 生成二维码
     */
    @GetMapping("/createNative/{orderId}")
    public Result createNative(
            @ApiParam(name = "orderId", value = "订单id", required = true)
            @PathVariable("orderId") Long orderId) {
        return Result.ok(weixinPayService.createNative(orderId));
    }

    @ApiOperation("支付状态查询")
    @GetMapping("/queryPayStatus/{orderId}")
    public Result queryPayStatus(@ApiParam(name = "orderId",value = "订单编号",required = true)
                                 @PathVariable Long orderId){
        Map<String, String> resultMap = weixinPayService.queryPayStatus(orderId, PaymentTypeEnum.WEIXIN.name());
        if(StringUtils.isEmpty(resultMap)){
            return Result.fail().message("支付失败");
        }
        if("SUCCESS".equals(resultMap.get("result_code"))){
            String tradeNo = resultMap.get("out_trade_no");
            paymentService.paySuccess(tradeNo,PaymentTypeEnum.WEIXIN.getStatus(),resultMap);
            return Result.ok().message("支付成功");
        }

        return Result.ok().message("支付中");

    }
}